package handle

import (
	"server/share/config"
	"server/social/graph"
	"server/social/model"

	"github.com/hwcer/cosgo/slice"
	"github.com/hwcer/cosgo/times"
	"github.com/hwcer/cosgo/utils"
	"github.com/hwcer/logger"
	"github.com/hwcer/yyds/context"
	"github.com/hwcer/yyds/errors"
	"github.com/hwcer/yyds/players/player"
)

// Like 点赞
func (this *Friend) Like(c *context.Context) any {
	uid := c.Uid()
	s := c.GetString("uidList")
	if s == "" {
		return errors.ErrArgEmpty
	}
	likesMaxNum := config.Data.Base["likesMaxNum"]
	if likesMaxNum == nil {
		return c.Error("config Base likesMaxNum not exist")
	}
	likesGiftItem := config.Data.Base["likesGiftItem"]
	if likesGiftItem == nil || likesGiftItem.Val == 0 {
		return c.Error("config Base likesGiftItem not exist")
	}

	arr := slice.Split(s, ",")
	arr = slice.Unrepeated(arr)
	if len(arr) == 0 {
		return errors.ErrArgEmpty
	}
	now := c.Unix()
	today := times.Daily(0).Now().Unix()
	var success []string

	_ = model.Graph.Modify(uid, func(p *graph.Player) error {
		//整理无效的
		likes := map[string]int64{}
		for k, v := range p.Likes {
			if v >= today {
				likes[k] = v
			}
		}
		for _, fid := range arr {
			if fid == uid {
				continue
			}
			if _, ok := likes[fid]; !ok {
				likes[fid] = now
				success = append(success, fid)
			}
		}
		p.Likes = likes
		return nil
	})
	v := len(success)
	if v == 0 {
		return nil
	}

	///礼物
	num := c.Player.Val(config.Data.DailyKey.LikeNum)
	if n := int64(likesMaxNum.Val) - num; n > 0 {
		n = utils.Min(n, int64(v))
		c.Player.Add(likesGiftItem.Val, n)
	}
	c.Player.Emit(config.Data.Events.LikeNum, int32(v))

	m := c.Mutex()
	m.Async(arr, nil, this.likeUpdate)

	return true
}

func (this *Friend) likeUpdate(locker player.Locker, _ any) {
	key := config.Data.RoleFields.Like
	locker.Select(key)
	if err := locker.Data(); err != nil {
		logger.Error(err)
		return
	}
	locker.Range(func(p *player.Player) bool {
		like := p.Val(key)
		p.Set(key, like+1)
		return true
	})
	_ = locker.Submit()
}
